import defaultSettings from '@/settings'
import {
  getSetting
} from '@/api/system/setting'


let config = {};
const {
  sideTheme,
  showSettings,
  topNav,
  tagsView,
  fixedHeader,
  sidebarLogo,
  dynamicTitle
} = defaultSettings

const storageSetting = JSON.parse(localStorage.getItem('layout-setting')) || ''
const state = {
  title: '',
  theme: storageSetting.theme || '#409EFF',
  sideTheme: storageSetting.sideTheme || sideTheme,
  showSettings: showSettings,
  topNav: storageSetting.topNav === undefined ? topNav : storageSetting.topNav,
  tagsView: storageSetting.tagsView === undefined ? tagsView : storageSetting.tagsView,
  fixedHeader: storageSetting.fixedHeader === undefined ? fixedHeader : storageSetting.fixedHeader,
  sidebarLogo: storageSetting.sidebarLogo === undefined ? sidebarLogo : storageSetting.sidebarLogo,
  dynamicTitle: storageSetting.dynamicTitle === undefined ? dynamicTitle : storageSetting.dynamicTitle,
  settingConfig: {},
}


const mutations = {
  CHANGE_SETTING: (state, {
    key,
    value
  }) => {
    if (state.hasOwnProperty(key)) {
      state[key] = value
    }
  },
  SET_SETTING: (state, settingConfig) => {
    state.settingConfig = settingConfig;
  }
}

const actions = {
  // 修改布局设置
  changeSetting({
    commit
  }, data) {
    commit('CHANGE_SETTING', data)
  },
  // 设置网页标题
  setTitle({
    commit
  }, title) {
    state.title = title
  },
  // 获取系统配置
  fetchSetting({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      getSetting().then(res => {
        commit('SET_SETTING', res.data)
        config = state.settingConfig
        state.title = config.title,
          state.theme = storageSetting.theme || config.color,
          state.sideTheme = storageSetting.sideTheme || config.sideTheme,
          state.showSettings = config.showSettings,
          state.topNav = storageSetting.topNav === undefined ? config.topNav : storageSetting.topNav,
          state.tagsView = storageSetting.tagsView === undefined ? config.tagsView : storageSetting.tagsView,
          state.fixedHeader = storageSetting.fixedHeader === undefined ? config.fixedHeader : storageSetting.fixedHeader,
          state.sidebarLogo = storageSetting.sidebarLogo === undefined ? config.sidebarLogo : storageSetting.sidebarLogo,
          state.dynamicTitle = storageSetting.dynamicTitle === undefined ? config.dynamicTitle : storageSetting.dynamicTitle,
          resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },






}



export default {
  namespaced: true,
  state,
  mutations,
  actions
}
